package com.example.springbootflowabledemo.config;

import com.example.springbootflowabledemo.constant.ContextHolderConstants;
import com.example.springbootflowabledemo.domian.pojo.sys.SysUser;
import com.example.springbootflowabledemo.exception.ServiceException;
import com.example.springbootflowabledemo.service.sys.SysUserService;
import com.example.springbootflowabledemo.util.ContextHolderUtil;
import com.example.springbootflowabledemo.util.JwtUtil;
import com.example.springbootflowabledemo.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class HeaderInterceptor implements AsyncHandlerInterceptor {

    /**
     * 访问控制器方法前执行
     */

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        log.info("preHandle>>>> ServletPath={}", request.getServletPath());

        String token = request.getHeader(ContextHolderConstants.TOKEN);
        SysUser user = JwtUtil.verity(token);
        SysUserService userService = SpringUtil.getBean(SysUserService.class);
        user = userService.getById(user.getId());
        if (user == null) {
            throw new ServiceException("当前用户不存在!");
        }
        ContextHolderUtil.set(ContextHolderConstants.USER_ID, user.getId());
        ContextHolderUtil.set(ContextHolderConstants.NICKNAME, user.getNickname());
        return true;
    }
}
